funcfunc2(){ const filename = "aaa.txt" // 或者将读取文件和 if 写在同一行 if contents, err := ioutil.ReadFile(filename); err!=nil{ fmt.Println(err) }else{ fmt.Printf("%s\n", contents) } // 此处会出错,因为变量 contents 是在 if 中定义的,作用域为 if 以内 // fmt.Println(contents) }
funcgrade( score int)string { // go 中 switch 会自动 break,除非使用 fallthrough // switch 后面可以不跟表达式,直接写在 case 后面即可 g := "" switch { case score<0 || score > 100: panic(fmt.Sprintf("Wrong score: %d", score)) // panic 表示异常,终止程序继续往下运行 case score < 60: g = "F" case score < 80: g = "C" case score < 90: g = "B" case score < 100: g = "A" } return g }
funcmain() { number := 100 switch { case number > 10: fmt.Println("> 10") fallthrough// 穿透下一层级。会打印 '> 10' 和 '>20' case number > 20: fmt.Println("> 20") case number > 30: fmt.Println("> 30") } }
switch 结合 type 判断类型
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
package main
import"fmt"
funcmain() { // 定义一个 interface var number interface{} // 给 number 赋值 number = 3.1415926 // 根据值判断出类型,然后结合 switch switch number.(type) { casefloat32: fmt.Println("float32") casefloat64: fmt.Println("float64") // float64 会被输出 default: fmt.Println("unknow") } }